var instance = false;
var error_func;
var state;
var mes;
var file;
var cur_error = false;

function Chat() {
	this.update = updateChat;
	this.send = sendChat;
	this.getState = getStateOfChat;
	this.validateUsername = validateUsername;
	this.retryChat = retryChat;
}

//validates a username
function validateUsername() {

    //ask use for name with pop prompt
    var username = prompt("Enter your chat name:", "Guest");

    if(username) {
        //strip tags
        username = username.replace(/(<([^>]+)>)/ig, "");

        $.ajax({
            type: "POST",
            url: "process.php",
            data: { 'function': 'validateUsername', 'username': username, 'file': file },
            dataType: "json",
            success:
                function(data) {
                    if(data.accepted === 'true') {
                         $('#username').text(data.username);
                        clear_error();
                    }
                    else {
                        $('#username').text('<none>');
                        show_error("Username taken. Click to try again. They expire after 2 mins of non-use.", 'chat.validateUsername()');
                    }
                }
        });

        return username;
    }
}

// displays an error
function show_error(error_msg, error_func) {

    $('#server-msg').text(error_msg);
    $('#server-msg').attr('class', 'error-msg');
    if(error_func) {
        $('#server-msg').attr('onclick', error_func);
        $('#server-msg').css('cursor', 'pointer');
    }

    cur_error = true;
}

function clear_error() {
    $('#server-msg').attr('class', 'hide-msg');
    $('#server-msg').removeAttr('onclick');
    $('#server-msg').css('cursor', 'auto');

    cur_error = false;
}
	
//gets the state of the chat
function getStateOfChat() { 
	if (!instance) {
		instance = true;
		$.ajax({
		    type: "POST",
		    url: "process.php",
		    data: { 'function': 'getState', 'file': file },
		    dataType: "json",
		    success:
				function(data) {
				    state = data.state;
                    instance = false;
				}
		});
	}
}

function retryChat() {
    clear_error();
    instance = false;
    updateChat();
}

//updates the chat
function updateChat() {
	if(!instance) {
		instance = true;

		$.ajax({
		    type: "POST",
		    url: "process.php",
		    data: { 'function': 'update', 'state': state, 'file': file },
		    dataType: "json",
		    success:
				function(data) {

				    // append new lines to the char-area
				    if(data.text) {
				        for(var i = 0; i < data.text.length; i++) {
				            $('#chat-area').append($(data.text[i]));
				        }
				    }

				    $('#username').text(data.username);
				    document.getElementById('chat-area').scrollTop =
						document.getElementById('chat-area').scrollHeight;
				    instance = false;
				    state = data.state;

				    // error checking:
				    if(data.error === 'not_logged_in' && !cur_error) {
				        show_error("Please click here to choose a username", 'chat.validateUsername()');
				    }
				},
		    error:
                function(jqXKR, textStatus) {
                    show_error("Connection Error: " + textStatus + ", Click to retry connection",
                               'chat.retryChat()');
                }
		});
	}
	else {
		setTimeout(updateChat, 1500); 
	}		
}

//send the message
function sendChat(message, username) {
	updateChat();
	$.ajax({
	    type: "POST",
	    url: "process.php",
	    data: { 'function': 'send', 'message': message, 'username': username,
	        'file': file
	    },
	    dataType: "json",
	    success:
			function(data) {

			    updateChat();
			},
	    statusCode: {
	        404: function() {
	            alert("page not found");
	        },
	        500: function() {
	            alert("PHP error");
	        }
	    }
	});
}		
		
